<?php

use app\components\BaseApp;
use NoahBuscher\Macaw\Macaw;

/**
 * class App
 *
 * @property  \PDO $pdo
 * @property  \app\components\SFLogger $logger
 * @property  \app\components\SFLogger $taskLog
 *
 * @method static \PDO pdo()
 * @method static \app\components\SFLogger logger()
 * @method static \app\components\SFLogger taskLog()
 */
class App extends BaseApp
{

    /**********************************************************
     * app run
     **********************************************************/

    /**
     * @inheritdoc
     */
    public function doRun()
    {
        try {
            // if 'onNotFound' service is registered.
            if ( $notFoundHandler = self::get(self::EVT_NOT_FOUND, false) ) {
                Macaw::$error_callback = $notFoundHandler;
            }

            // 匹配到一个就不在继续匹配
            Macaw::haltOnMatch();
            Macaw::dispatch();
        } catch (Exception $e) {
            $this->dispatchExHandler($e);
        }
    }

    /**
     * 运行异常处理
     * @param Exception $e
     * @throws Exception
     */
    public function dispatchExHandler(\Exception $e )
    {
        $this->logger->ex($e);

        // open debug, throw exception
        if ( $this->config['debug'] ) {
            throw $e;
        }

        // no output
        echo 'An error occurred!';
    }

    public static function parseConsoleArgs($argv)
    {
        // fixed: '/home' is not equals to '/home/'
        if (isset($_SERVER['REQUEST_URI'])) {
            $_SERVER['REQUEST_URI'] = rtrim($_SERVER['REQUEST_URI'],'/ ');
        }

        // fixed: PHP_SELF = 'index.php', it is should be '/index.php'
        if (isset($_SERVER['PHP_SELF'])) {
            $_SERVER['PHP_SELF'] = '/' . ltrim($_SERVER['PHP_SELF'],'/ ');
        }

        $script = array_shift($argv);

        // show help `./bin/app -h`
        $help = getopt('h::', ['help::']);
        if ($help && (isset($help['h']) || isset($help['help']))) {
            echo " Usage: $script [route] [args ...]\n",
                " example:\n  $script home/index arg1=value1 arg2=value\n",
                " Notice: 'home/index' don't write '/home/index'\n\n";

            exit(0);
        }

        $_SERVER['PHP_SELF'] = '/app';
        $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
        $_SERVER['REQUEST_METHOD'] = 'GET';
        $_SERVER['REQUEST_URI'] = '/';

        if ( isset($argv[0]) && strpos($argv[0], '=') === false ) {
            $path = trim(array_shift($argv), '/');

            $_SERVER['REQUEST_URI'] .= $path;
        }

        // parse query params
        if ($argv) {
            parse_str(implode('&',$argv), $data);
            $_REQUEST = $_GET = $data;
        }
    }


}
